<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useCampfireStore } from '../stores/campfireStore'
import { useMindArchiveStore } from '../stores/mindArchiveStore'
import { useContainerStore } from '../stores/containerStore'
import { ArrowLeft, Plus, Delete } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const campfireStore = useCampfireStore()
const mindArchiveStore = useMindArchiveStore()
const containerStore = useContainerStore()

// 表单数据
const postForm = ref({
  title: '',
  description: '',
  tags: [],
  archiveId: '',
  investedTime: 0,
  blockingPoint: '',
  customTag: ''
})

// 表单规则
const rules = {
  title: [{ required: true, message: '请输入帖子标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入帖子描述', trigger: 'blur' }],
  tags: [{ required: true, message: '请至少添加一个标签', trigger: 'change' }],
  blockingPoint: [{ required: true, message: '请描述你遇到的卡点', trigger: 'blur' }]
}

// 表单引用
const formRef = ref(null)

// 获取思维存档列表
const archives = computed(() => mindArchiveStore.activeArchives)

// 选择的思维存档
const selectedArchive = ref(null)

// 从路由参数获取存档ID
onMounted(() => {
  const { archiveId } = route.query
  if (archiveId) {
    selectArchive(archiveId)
  }
})

// 选择思维存档
function selectArchive(archiveId) {
  const archive = archives.value.find(a => a.id === archiveId)
  if (archive) {
    selectedArchive.value = archive
    
    // 填充表单数据
    postForm.value.title = `求助：${archive.title}`
    postForm.value.description = archive.description
    postForm.value.tags = [...archive.tags] // 复制标签数组
    postForm.value.archiveId = archive.id
    postForm.value.blockingPoint = archive.blockingPoint || ''
    
    // 如果存档关联了容器，获取投入时间
    if (archive.containerId) {
      const container = containerStore.containers.find(c => c.id === archive.containerId)
      if (container) {
        postForm.value.investedTime = container.actualTime || 0
      }
    }
  }
}

// 添加自定义标签
function addCustomTag() {
  if (postForm.value.customTag && !postForm.value.tags.includes(postForm.value.customTag)) {
    postForm.value.tags.push(postForm.value.customTag)
    postForm.value.customTag = ''
  }
}

// 移除标签
function removeTag(tag) {
  const index = postForm.value.tags.indexOf(tag)
  if (index !== -1) {
    postForm.value.tags.splice(index, 1)
  }
}

// 提交表单
function submitForm() {
  formRef.value.validate((valid) => {
    if (valid) {
      // 创建帖子
      const postId = campfireStore.createPost({
        title: postForm.value.title,
        description: postForm.value.description,
        tags: postForm.value.tags,
        archiveId: postForm.value.archiveId,
        investedTime: postForm.value.investedTime,
        blockingPoint: postForm.value.blockingPoint
      })
      
      // 跳转到帖子详情页
      router.push(`/campfire/post/${postId}`)
    }
  })
}

// 返回上一页
function goBack() {
  router.back()
}
</script>

<template>
  <div class="create-post-container">
    <div class="page-header">
      <el-button @click="goBack" text>
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h1 class="page-title">分享到探索营地</h1>
    </div>
    
    <div class="archive-selection" v-if="!selectedArchive">
      <h2 class="section-title">选择一个思维存档</h2>
      <p class="section-desc">从你的思维存档中选择一个分享到社区</p>
      
      <div class="archives-list">
        <template v-if="archives.length > 0">
          <div 
            v-for="archive in archives" 
            :key="archive.id"
            class="archive-card"
            @click="selectArchive(archive.id)"
          >
            <h3 class="archive-title">{{ archive.title }}</h3>
            <p class="archive-desc">{{ archive.description }}</p>
            <div class="archive-tags">
              <el-tag 
                v-for="tag in archive.tags" 
                :key="tag"
                size="small"
                effect="plain"
              >
                {{ tag }}
              </el-tag>
            </div>
            <div class="archive-time">创建于 {{ archive.archiveTime }}</div>
          </div>
        </template>
        
        <div v-else class="empty-state">
          <el-empty description="暂无思维存档" />
          <el-button type="primary" @click="router.push('/mind-archive')">创建思维存档</el-button>
        </div>
      </div>
    </div>
    
    <div class="post-form" v-if="selectedArchive">
      <div class="selected-archive-info">
        <h3>已选择思维存档：{{ selectedArchive.title }}</h3>
        <el-button text @click="selectedArchive = null">更换</el-button>
      </div>
      
      <el-form 
        ref="formRef"
        :model="postForm"
        :rules="rules"
        label-position="top"
      >
        <el-form-item label="帖子标题" prop="title">
          <el-input v-model="postForm.title" placeholder="请输入帖子标题" />
        </el-form-item>
        
        <el-form-item label="帖子描述" prop="description">
          <el-input 
            v-model="postForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请描述你的问题背景和上下文"
          />
        </el-form-item>
        
        <el-form-item label="卡点描述" prop="blockingPoint">
          <el-input 
            v-model="postForm.blockingPoint" 
            type="textarea" 
            :rows="3"
            placeholder="请详细描述你遇到的具体卡点或困难"
          />
        </el-form-item>
        
        <el-form-item label="标签" prop="tags">
          <div class="tags-input">
            <div class="tags-list">
              <el-tag 
                v-for="tag in postForm.tags" 
                :key="tag"
                closable
                @close="removeTag(tag)"
                class="tag-item"
              >
                {{ tag }}
              </el-tag>
            </div>
            
            <div class="add-tag-input">
              <el-input 
                v-model="postForm.customTag"
                placeholder="添加标签"
                @keyup.enter="addCustomTag"
              >
                <template #append>
                  <el-button @click="addCustomTag">
                    <el-icon><Plus /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </div>
          </div>
          <div class="tags-hint">添加相关标签，如技术领域、学科、具体问题类型等</div>
        </el-form-item>
        
        <el-form-item label="已投入时间">
          <el-input-number 
            v-model="postForm.investedTime" 
            :min="0"
            :step="5"
          />
          <span class="time-unit">分钟</span>
          <div class="time-hint">这将显示为「已探索时间」，表明你为解决这个问题已经付出的努力</div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">发布到探索营地</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.create-post-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.page-title {
  margin: 0 0 0 20px;
  font-size: 24px;
}

.section-title {
  font-size: 20px;
  margin: 0 0 5px;
}

.section-desc {
  color: #666;
  margin: 0 0 20px;
}

.archives-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.archive-card {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.archive-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #ddd;
}

.archive-title {
  margin: 0 0 10px;
  font-size: 16px;
}

.archive-desc {
  color: #666;
  margin: 0 0 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.archive-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 10px;
}

.archive-time {
  font-size: 12px;
  color: #999;
}

.selected-archive-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.tags-input {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  margin-right: 0;
}

.add-tag-input {
  width: 100%;
}

.tags-hint, .time-hint {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.time-unit {
  margin-left: 10px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 40px 0;
  grid-column: 1 / -1;
}
</style>